<template>
  <div class="shelf-footer" v-show="isEditMode">
    <div class="shelf-footer-tab-wrapper"
         v-for="item in tabs" :key="item.index"
         @click="onTabClick(item)">
      <div class="shelf-footer-tab" :class="{'is-selected': isSelected}">
        <div :class="item.icon" class="tab-icon"></div>
        <div class="tab-text">{{label(item)}}</div>
      </div>
    </div>
  </div>
</template>

<script>
  import { storeShelfMixin } from '../../utils/mixin'
  import { removeLocalStorage, saveBookShelf } from '../../utils/localStorage'
  import { download } from '../../api/store'
  import { removeLocalForage } from '../../utils/localForage'
  export default {
    mixins: [storeShelfMixin],
    data() {
      return {
        popupMenu: null
      }
    },
    computed: {
      isSelected() {
        return this.shelfSelected.length
      },
      tabs() {
        return [
          {
            icon: this.isPrivate ? 'icon-private-see' : 'icon-private',
            label: this.$t('shelf.private'),
            label2: this.$t('shelf.noPrivate'),
            index: 1
          },
          {
            icon: this.isDownload ? 'icon-download-remove' : 'icon-download',
            label: this.$t('shelf.download'),
            label2: this.$t('shelf.delete'),
            index: 2
          },
          {
            icon: 'icon-move',
            label: this.$t('shelf.move'),
            index: 3
          },
          {
            icon: 'icon-shelf',
            label: this.$t('shelf.remove'),
            index: 4
          }
        ]
      },
      isPrivate() {
        if (!this.isSelected) {
           return false
        } else {
          return this.shelfSelected.every(item => item.private)
        }
      },
      isDownload() {
        if (!this.isSelected) {
          return false
        } else {
          return this.shelfSelected.every(item => item.cache)
        }
      }
    },
    methods: {
      async downloadSelectedBook() {
        console.log(this.shelfSelected)
        for (let i = 0; i < this.shelfSelected.length; i++) {
           await this.downloadBook(this.shelfSelected[i]).then(book => {
             console.log('cache book', book)
             book.cache = true
          })
        }
        this.setShelfList(this.shelfList)
        saveBookShelf(this.shelfList)
      },
      downloadBook(book) {
        let text = ''
        const toast = this.toast({
          text: text
        })
        toast.continueShow()
        return new Promise((resolve, reject) => {
          download(book, (res) => {
            toast && toast.remove()
            resolve(book)
          }, reject, progressEvent => {
            const progress = Math.floor(progressEvent.loaded / progressEvent.total * 100)
            const text = this.$t('shelf.progressDownload').replace('$1', `${book.fileName}.epub(${progress})`)
            toast.updateText(text)
          })
        })
      },
      removeSelectedBookCache() {
        Promise.all(this.shelfSelected.map(book => this.removeBookCache(book)))
          .then(books => {
//            books.map(book => {
//              book.cache = false
//            })
            saveBookShelf(this.shelfList)
          })
      },
      removeBookCache(book) {
        return new Promise((resolve, reject) => {
          removeLocalStorage(`${book.categoryText}/${book.fileName}-info`)
          removeLocalForage(`${book.fileName}`)
          book.cache = false
          resolve(book)
        })
      },
      hidePopup() {
        this.popupMenu.hide()
      },
      setPrivate() {
        let isPrivate
        if (this.isPrivate) {
          isPrivate = false
        } else {
          isPrivate = true
        }
        this.shelfSelected.forEach(book => {
          book.private = isPrivate
        })
        this.hidePopup()
        this.setIsEditMode(false)
        if (isPrivate) {
          this.simpleToast(this.$t('shelf.setPrivateSuccess'))
        } else {
          this.simpleToast(this.$t('shelf.closePrivateSuccess'))
        }
        saveBookShelf(this.shelfList)
      },
      async setDownload() {
        this.hidePopup()
        this.setIsEditMode(false)
        if (this.isDownload) {
          this.removeSelectedBookCache()
          this.simpleToast(this.$t('shelf.removeDownloadSuccess'))
        } else {
          await this.downloadSelectedBook()
          this.simpleToast(this.$t('shelf.setDownloadSuccess'))
        }
      },
      removeSelectedBook() {
        this.shelfSelected.forEach(selected => {
          this.setShelfList(this.shelfList.filter(book => book.id !== selected.id))
        })
        saveBookShelf(this.shelfList)
        this.setIsEditMode(false)
        this.hidePopup()
      },
      showPrivate () {
        this.popupMenu = this.popup({
          title: this.isPrivate ? this.$t('shelf.closePrivateTitle') : this.$t('shelf.setPrivateTitle'),
          btns: [
            {
              text: this.isPrivate ? this.$t('shelf.close') : this.$t('shelf.open'),
              click: () => {
                this.setPrivate()
              }
            },
            {
              text: '取消',
              click: () => {
                this.hidePopup()
              }
            }
          ]
        })
        this.popupMenu.show()
      },
      showDownload() {
        this.popupMenu = this.popup({
          title: this.isDownload ? this.$t('shelf.removeDownloadTitle') : this.$t('shelf.setDownloadTitle'),
          btns: [
            {
              text: this.isDownload ? this.$t('shelf.delete') : this.$t('shelf.download'),
              click: () => {
                this.setDownload()
              }
            },
            {
              text: '取消',
              click: () => {
                this.hidePopup()
              }
            }
          ]
        })
        this.popupMenu.show()
      },
      showRemove() {
        let title
        if (this.shelfSelected.length === 1) {
          title = this.$t('shelf.removeBookTitle').replace('$1', `<<${this.shelfSelected[0].title}>>`)
        } else {
          title = this.$t('shelf.removeBookTitle').replace('$1', this.$t('shelf.selectedBooks'))
        }
        this.popupMenu = this.popup({
          title: title,
          btns: [
            {
              text: this.$t('shelf.delete'),
              type: 'danger',
              click: () => {
                this.removeSelectedBook()
              }
            },
            {
              text: '取消',
              click: () => {
                this.hidePopup()
              }
            }
          ]
        })
        this.popupMenu.show()
      },
      onTabClick(item) {
        if (!this.isSelected) {
          return
        }
        switch (item.index) {
          case 1:
            this.showPrivate()
            break
          case 2:
            this.showDownload()
            break
          case 3:
            this.dialog().show()
            break
          case 4:
            this.showRemove()
            break
          default:
        }
      },
      label(item) {
        switch (item.index) {
          case 1:
            return this.isPrivate ? item.label2 : item.label
          case 2:
            return this.isDownload ? item.label2 : item.label
          default:
            return item.label
        }
      }
    }
  }
</script>

<style lang="scss"
       rel="stylesheet/scss" scoped>
    @import "../../assets/styles/global";
  .shelf-footer {
    position: fixed;
    display: flex;
    bottom: 0;
    left: 0;
    height: px2rem(48);
    width: 100%;
    background: white;
    z-index: 120;
    box-shadow: 0 px2rem(-2) px2rem(2) 0 rgba(0, 0, 0, .1);
    .shelf-footer-tab-wrapper {
      flex: 1;
      .shelf-footer-tab {
        width: 100%;
        height: 100%;
        @include columnCenter;
        opacity: .5;
        &.is-selected {
          opacity: 1;
        }
        .tab-icon {
          font-size: px2rem(20);
          color: #666;
        }
        .tab-text {
          font-size: px2rem(12);
          margin-top: px2rem(5);
        }
      }
    }
  }
</style>
